<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );

/**
 * 配送员
 * 
 * @author Administrator
 *        
 */
class Member extends MY_Controller {
	
	/**
	 *
	 * @var DlnUserModel
	 */
	public $mMember = null;
	
	/**
	 * @var DlnOrderModel
	 */
	public $mOrder = null;
	
	public function __construct() {
		parent::__construct ();
		$this->loadModel ( 'DlnUserModel', 'mMember', 'deliveryman' );
	}
	
	/**
	 * 首页
	 */
	public function index() {
		$this->loadModel('AdmSettingModel', 'mSetting', 'admin');
		$tA = $this->mUser->getCountyIds($this->userId, true);
		$id = array_merge($tA['province'], $tA['city'], $tA['county']);
		$data = [ 
				'status' => $this->mMember->status (),
				'type' => $this->mMember->type (),
				'province' => $this->mSetting->getProvinces($id)
		];
		$this->view ('deliveryman/member/home', $data, 'datatable,datepicker,webuploader,validation,uniform,select2' );
	}
	
	/**
	 * 会员列表
	 */
	public function getList() {
		$dateFrom = get ( 'date_from' );
		$dateTo = get ( 'date_to' );
		$name = trim ( get ( 'name' ) );
		$mobile = trim ( get ( 'mobile' ) );
		$type = ( int ) get ( 'type' );
		$score = ( int ) get ( 'score' );
		$status = ( int ) get ( 'status' );
		$sort = ( int ) get ( 'iSortCol_0' );
		$sortType = get ( 'sSortDir_0' );
		$province = get ( 'province' );
		$city = get ( 'city' );
		$county = get ( 'county' );
		if ( ! in_array ( $sortType, [ 
				'asc',
				'desc' 
		] )) {
			$sortType = '';
		}
		
		$this->db->select ( 'id,type,name,mobile,type,status,amount,addtime,score,order_total,
				order_complete_total,order_overtime_total,province_id,city_id,county_id')
				 ->where_in('county_id', $this->countyItem);
		
		if($province){
			$this->db->where('province_id', $province);
		}
		
		if($city){
			$this->db->where('city_id', $city);
		}
		
		if($county && $county[0] && is_array($county)){
			$this->db->where_in('county_id', $county);
		}
				 
		if ($dateFrom) {
			$this->db->where ( 'addtime >=', strtotime ( $dateFrom ) );
		}
		
		if ($dateTo) {
			$this->db->where ( 'addtime <', strtotime ( '+1day', strtotime ( $dateTo ) ) );
		}
		
		if ($name) {
			$this->db->like ( 'name', $name );
		}
		
		if ($mobile) {
			$this->db->where ( 'mobile', $mobile );
		}
		
		if ($type) {
			$this->db->where ( 'type', $type );
		}
		
		if ($score) {
			$this->db->where ( 'score', $score );
		}
		
		if ($status) {
			$this->db->where ( 'status', $status );
		}
		
		if ($sort && $sortType) {
			if ($sort == 6) {
				$this->db->order_by ( 'amount ' . $sortType );
			}elseif ($sort == 7) {
				$this->db->order_by ( 'order_total ' . $sortType );
			}elseif ($sort == 8) {
				$this->db->order_by ( 'order_complete_total ' . $sortType );
			}elseif ($sort == 9) {
				$this->db->order_by ( 'order_overtime_total ' . $sortType );
			}else{
				$this->db->order_by ( 'id desc' );
			}
		}else{
			$this->db->order_by ( 'id desc' );
		}
		
		$data = $this->mMember->pagination ( $this->mMember->tbUser);
		$addressId = [];
		foreach ($data['data'] as $v){
			if( ! in_array($v['province_id'], $addressId)){
				$addressId[] = $v['province_id'];
			}
			if( ! in_array($v['city_id'], $addressId)){
				$addressId[] = $v['city_id'];
			}
			if( ! in_array($v['county_id'], $addressId)){
				$addressId[] = $v['county_id'];
			}
		}
		
		$this->loadModel('AdmSettingModel', 'mSett', 'admin');
		$address = $this->mSett->getLocationNameByIds($addressId);
		foreach ( $data ['data'] as $k => $v ) {
			$data ['aaData'] [$k] [] = dateFormat ( $v ['addtime']);
			$data ['aaData'] [$k] [] = $v ['name'];
			$tS = isset($address[$v['province_id']]) ? $address[$v['province_id']]['name'] : '';
			$tSs = isset($address[$v['city_id']]) ? $address[$v['city_id']]['name'] : '';
			$tS .= $tSs == $tS ? '' : $tSs;
			$tS .= isset($address[$v['county_id']]) ? $address[$v['county_id']]['name'] : '';
			$data ['aaData'] [$k] [] = $tS;
			$data ['aaData'] [$k] [] = $v ['mobile'];
			$data ['aaData'] [$k] [] = $this->mMember->type ( $v ['type'] );
			$data ['aaData'] [$k] [] = $v ['score'] ? $v ['score'] : '<span style="color:grey;">暂无评分</span>';
			$data ['aaData'] [$k] [] = $v ['amount'] ? $v ['amount'] : 0;
			$data ['aaData'] [$k] [] = ( int ) $v ['order_total'];
			$data ['aaData'] [$k] [] = ( int ) $v ['order_complete_total'];
			$data ['aaData'] [$k] [] = ( int ) $v ['order_overtime_total'];
			$data ['aaData'] [$k] [] = $this->mMember->status ( $v ['status'], true );
			$btnConfig = array (
					array (
							'label' => '详情',
							'icon' => '<i class="fa fa-eye"></i>',
							'attr' => array (
									'href' => getUrl ( 'deliveryman/member/details?id=' . $v ['id'] ),
									'class' => 'btn btn-xs btn-default' 
							),
							'tag' => 'a' 
					) 
			);
			
			if ($v ['status'] == 5) {
				$btnConfig [] = array (
						'label' => '审核',
						'icon' => '',
						'attr' => array (
								'href' => getUrl ( 'deliveryman/member/getInfo?id=' . $v ['id'] ),
								'class' => 'auth-btn' 
						),
						'tag' => 'a'
				);
			}
			
			if ($v ['status'] == 2 || $v ['status'] == 4) {
				$btnConfig [] = array (
						'label' => '编辑',
						'icon' => '',
						'attr' => array (
								'href' => getUrl ( 'deliveryman/member/getInfo?id=' . $v ['id'] ),
								'class' => 'edit-btn' 
						),
						'tag' => 'a'
				);
			}
			$data ['aaData'] [$k] [] = adminCreateBtn ( $btnConfig );
		}
		unset ( $data ['data'] );
		echo json_encode ( $data );
	}
	
	/**
	 * 销售金额
	 */
	public function getAmountList() {
		$dateFrom = get ( 'date_from' );
		$dateTo = get ( 'date_to' );
		$type = trim ( get ( 'type' ) );
		$status = ( int ) get ( 'status' );
		$sort = ( int ) get ( 'iSortCol_0' );
		$sortType = get ( 'sSortDir_0' );
		$id = get ( 'id' );
		if (! in_array ( $sortType, [ 
				'asc',
				'desc' 
		] )) {
			$sortType = '';
		}
		
		$this->db->select ('id,type,amount,status,addtime')
				->order_by ( 'id desc' )
				->where('deliveryman_id', $id);
		if ($dateFrom) {
			$this->db->where ( 'addtime >=', strtotime ( $dateFrom ) );
		}
		
		if ($dateTo) {
			$this->db->where ( 'addtime <', strtotime ( '+1day', strtotime ( $dateTo ) ) );
		}
		
		if ($type) {
			$this->db->where ( 'type', $type );
		}
		
		if ($status) {
			$this->db->where ( 'status', $status );
		}
		
		
		$data = $this->mMember->pagination ( $this->mMember->tbAmountDetails );
		foreach ( $data ['data'] as $k => $v ) {
			$data ['aaData'] [$k] [] = dateFormat ( $v ['addtime'], true );
			$data ['aaData'] [$k] [] = $this->mMember->amountDetailsType($v['type']);
			$data ['aaData'] [$k] [] = $this->mMember->amountDetailsStatus($v['status']);
			$data ['aaData'] [$k] [] = $v ['amount'] > 0 ? '<span style="color:#3cc051;">+'.$v ['amount'].'</span>' 
					: '<span style="color:red;">'.$v ['amount'].'</span>';
			$data ['aaData'] [$k] [] = '';
		}
		unset ( $data ['data'] );
		echo json_encode ( $data );
	}
	
	/**
	 * 获取会员详情
	 */
	public function getInfo() {
		$id = ( int ) get ( 'id' );
		$info = $this->mMember->getInfo ( $id );
		if (! $info) {
			$this->ajaxReturn ( 0, '没有查询到相关会员信息' );
		}
		
		$this->ajaxReturn ( 1, '', $info );
	}
	
	/**
	 * 实名认证
	 */
	public function auth() {
		
		// 表单验证
		$vConf = array (
				array (
						'status',
						'状态',
						'required|in_list[1,2]' 
				),
				array (
						'id',
						'会员id',
						'required' 
				) 
		);
		$this->formDataValidation ( $vConf );
		
		$status = post ( 'status' );
		$id = post ( 'id' );
		$remarks = trim ( post ( 'remarks' ) );
		if ($status == 2 && ! $remarks) {
			$this->ajaxReturn ( 0, '请填写拒绝原因' );
		}
		
		if ($status == 2) {
			$status = 3;
		} else {
			$status = 2;
		}
		
		$data = [ 
				'status' => $status 
		];
		$this->db->where ( 'id', $id );
		if (! $this->mMember->update ( $this->mMember->tbUser, $data )) {
			$this->ajaxReturn ( 0, '审核失败' );
		}
		
		$data = [ 
				'deliveryman_id' => $id,
				'remarks' => $remarks,
				'addtime' => time () 
		];
		
		$this->db->where ( 'deliveryman_id', $id );
		$tI = $this->mMember->count ( $this->mMember->tbAuthRemarks );
		if ($tI) {
			$this->db->where ( 'deliveryman_id', $id );
			$this->mMember->update ( $this->mMember->tbAuthRemarks, $data );
		} else {
			$this->mMember->insert ( $this->mMember->tbAuthRemarks, $data );
		}
		
		$this->ajaxReturn ( 1, '已保存' );
	}
	
	/**
	 * 保存配送员信息
	 */
	public function save() {
		
		// 表单验证
		$vConf = array (
				array (
						'name',
						'姓名',
						'required|max_length[6]|valid_chinese' 
				),
				array (
						'type',
						'类型',
						'required|in_list[1,2]' 
				),
				array (
						'identity_card',
						'身份证',
						'required|valid_idcard' 
				),
				array (
						'mobile',
						'手机号码',
						'required|valid_mobile' 
				),
				array (
						'status',
						'状态',
						'required|in_list[1,2]' 
				),
				array (
						'id',
						'会员id',
						'integer' 
				),
				array ('province', '省份', 'required|is_natural_no_zero'),
				array ('city', '城市', 'required|is_natural_no_zero'),
				array ('county', '区县', 'required|is_natural_no_zero'),
		);
		$this->formDataValidation ( $vConf );
		$id = post ( 'id' );
		$status = post ( 'status' );
		$portrait = post ( 'portrait' );
		$mobile = trim ( post ( 'mobile' ) );
		$identityCardImg = post ( 'identity_card_img' );
		$province = post ( 'province' );
		$city = post ( 'city' );
		$county = post ( 'county' );
		
		if ($this->mMember->mobileIsExist ( $mobile, $id )) {
			$this->ajaxReturn ( 0, '手机号码已经注册' );
		}
		
		if( ! $id && adminAuthority('member-add', 'deliveryman')){
			$this->ajaxReturn ( 0, '无权限' );
		}
		
		$data = [ 
				'name' => trim ( post ( 'name' ) ),
				'type' => post ( 'type' ),
				'identity_card' => trim ( post ( 'identity_card' ) ),
				'province_id' => $province,
				'city_id' => $city,
				'county_id' => $county,
				'mobile' => $mobile,
				'status' => $status == 2 ? 2 : 4,
				'work_status' => 1
		];
		
		$tA = $this->mUser->getCountyIds($this->userId, true);
		
		if( ! in_array($province, $tA['province'])){
			$this->ajaxReturn(0, '无权限添加该省份的配送员');
		}
		
		if( ! in_array($city, $tA['city'])){
			$this->ajaxReturn(0, '无权限添加该城市的配送员');
		}
		
		if( ! in_array($county, $tA['county'])){
			$this->ajaxReturn(0, '无权限添加该区县的配送员');
		}
		
		$this->db->trans_begin ();
		$query = false;
		if (! $id) {
			if (! $portrait) {
				$this->db->trans_rollback ();
				$this->appReturn ( 0, '请上传头像' );
			}
			
			if (! $identityCardImg) {
				$this->db->trans_rollback ();
				$this->appReturn ( 0, '请上传身份证照片' );
			}
			$data ['password'] = setPassword ( substr ( $data ['mobile'], - 6 ) );
			$data ['addtime'] = time ();
			$query = $id = $this->mMember->insert ( $this->mMember->tbUser, $data );
		} else {
			$this->db->where ( 'id', $id );
			$query = $this->mMember->update ( $this->mMember->tbUser, $data );
		}
		
		if (! $query) {
			$this->db->trans_rollback ();
			$this->appReturn ( 0, '保存失败' );
		}
		
		$data = [ ];
		if ($portrait) {
			$path = 'uploads/deliveryman/' . $id;
			$query = saveTempImg ( $portrait, $path );
			if (! $query) {
				$this->db->trans_rollback ();
				$this->appReturn ( 0, '头像保存失败' );
			}
			
			$data ['portrait'] = $query;
		}
		
		if ($identityCardImg) {
			$path = 'uploads/deliveryman/' . $id;
			$query = saveTempImg ( $identityCardImg, $path );
			if (! $query) {
				$this->db->trans_rollback ();
				$this->appReturn ( 0, '身份证照片保存失败' );
			}
			
			$data ['identity_card_img'] = $query;
		}
		
		if ($data) {
			$this->db->where ( 'id', $id );
			if (! $this->mMember->update ( $this->mMember->tbUser, $data )) {
				$this->db->trans_rollback ();
				$this->appReturn ( 0, '保存失败' );
			}
		}
		
		$this->db->trans_commit ();
		$this->appReturn ( 1, '保存成功' );
	}
	
	/**
	 * 详情
	 */
	public function details() {
		$this->loadModel ( 'DlnOrderModel', 'mOrder', 'deliveryman' );
		$this->loadModel('AdmSettingModel', 'mSett', 'admin');
		$info = $this->mMember->getInfo ( get ( 'id' ) );
		if (! $info) {
			show_404 ();
		}
		$info ['status_str'] = $this->mMember->status ( $info ['status'], true );
		$info ['type'] = $this->mMember->type ( $info ['type'] );
		$info ['apconfig'] = $this->mOrder->apConfig();
		$info ['amount_type'] = $this->mMember->amountDetailsType();
		$info ['amount_status'] = $this->mMember->amountDetailsStatus();
		$info['ak'] = $this->mSett->get('map_key');
		$this->view ( 'deliveryman/member/detail', $info, 'datatable,datepicker' );
	}
	
	/**
	 * 定位
	 */
	public function postion() {
		$this->db->select ( 'longitude,latitude' )->where ( 'id', ( int ) get ( 'id' ) );
		$tA = $this->mMember->getOne ( $this->mMember->tbUser );
		if ($tA) {
			echo json_encode ( [ 
					$tA ['longitude'],
					$tA ['latitude'] 
			] );
			return;
		}
		
		echo json_encode ( [ ] );
	}
	
	/**
	 * 订单列表
	 */
	public function getOrderList() {
		$this->loadModel ( 'DlnOrderModel', 'mOrder', 'deliveryman' );
		$dateFrom = get ( 'date_from' );
		$dateTo = get ( 'date_to' );
		$code = trim ( get ( 'code' ) );
		$sendUser = trim ( get ( 'send_user' ) );
		$sendMobile = trim ( get ( 'send_mobile' ) );
		$sendToUser = trim ( get ( 'send_to_user' ) );
		$sendToMobile = trim ( get ( 'send_to_mobile' ) );
		$sendAddress = trim ( get ( 'send_address' ) );
		$sendToAddress = trim ( get ( 'send_to_address' ) );
		$deliveryman = trim ( get ( 'deliveryman' ) );
		$deliverymanMobile = trim ( get ( 'deliveryman_mobile' ) );
		$status = ( int ) get ( 'status' );
		$type = ( int ) get ( 'type' );
		$id = get ( 'id' );
		$apStatus = (int)get('ap_status');
		
		$this->db->select ( 'o.id,o.code,o.send_user,o.send_address, o.send_mobile,
				o.send_to_user,o.send_to_address,o.send_to_longitude,o.send_to_latitude,
				o.distance,o.send_to_mobile,o.status,o.addtime,o.expect_arrive_time,o.rob_expect_time,
				o.type,o.income,o.complete_time,ap.type as ap_type,ap.content as ap_content' )
		        ->join ( $this->mOrder->tbRelationOrder . ' ro', 'ro.order_id = o.id')
		        ->join($this->mOrder->tbOrderAp.' ap', 'ap.order_id = o.id', 'left')
		        ->where('ro.deliveryman_id', $id)
			    ->order_by ('o.id desc');
		
		if ($dateFrom) {
			$this->db->where ( 'o.addtime >=', strtotime ( $dateFrom ) );
		}
		
		if ($dateTo) {
			$this->db->where ( 'o.addtime <', strtotime ( '+1day', strtotime ( $dateTo ) ) );
		}
		
		if ($code) {
			$this->db->where ( 'o.code', $code );
		}
		
		if ($status) {
			$this->db->where ( 'o.status', $status );
		}
		
		if ($sendUser) {
			$this->db->like ( 'o.send_user', $sendUser );
		}
		
		if ($sendMobile) {
			$this->db->where ( 'o.send_mobile', $sendMobile );
		}
		
		if ($sendToUser) {
			$this->db->like ( 'o.send_to_user', $sendToUser );
		}
		
		if ($sendToMobile) {
			$this->db->where ( 'o.send_to_mobile', $sendToMobile );
		}
		
		if ($sendAddress) {
			$this->db->like ( 'o.send_address', $sendAddress );
		}
		
		if ($sendToAddress) {
			$this->db->like ( 'o.send_to_address', $sendToAddress );
		}
		
		if ($type) {
			$this->db->where ( 'o.type', $type );
		}
		
		if($apStatus){
			$this->db->where('ap.type', $apStatus);
		}
	
		$data = $this->mMember->pagination ( $this->mOrder->tbOrder . ' o' );
		foreach ( $data ['data'] as $k => $v ) {
			
			if ($v ['distance'] > 1000) {
				$v ['distance'] = ($v ['distance'] / 1000) . 'km';
			} else {
				$v ['distance'] = $v ['distance'] . 'm';
			}
			
			$data ['aaData'] [$k] [] = dateFormat ( $v ['addtime'], true );
			$data ['aaData'] [$k] [] = $v ['code'];
			$data ['aaData'] [$k] [] = $v ['send_user'] . '<br/><span style="color:grey;">（' . $v ['send_mobile'] . '）</span>';
			$data ['aaData'] [$k] [] = $v ['send_to_user'] . '<br/><span style="color:grey;">（' . $v ['send_to_mobile'] . '）</span>';
			$data ['aaData'] [$k] [] = $v ['send_address'];
			$data ['aaData'] [$k] [] = $v ['send_to_address'];
			$data ['aaData'] [$k] [] = $v ['distance'];
			$data ['aaData'] [$k] [] = $v ['income'];
			$data ['aaData'] [$k] [] = $this->mOrder->type ( $v ['type'] );
			$tI = ceil ( (($v ['status'] == 4 ? $v ['complete_time'] : time ()) - ($v ['status'] == 1 ? $v ['rob_expect_time'] : $v ['expect_arrive_time'])) / 60 );
			$show = '';
			if (abs ( $tI ) < 60) {
				$show = abs ( $tI ) . '分钟';
			} elseif (abs ( $tI ) > 60) {
				$e = abs ( $tI ) % 60;
				$show = floor ( abs ( $tI ) / 60 ) . '小时';
				if ($e > 0) {
					$show .= $e . '分钟';
				}
			}
			
			if ($tI > 0) {
				if ($v ['status'] == 4) {
					$show = '超时' . $show;
				} else {
					$show = '已超时' . $show;
				}
			} else {
				if ($v ['status'] == 4) {
					$show = '提前' . $show . '送达';
				} else {
					$show = $show . '后超时';
				}
			}
			
			$data ['aaData'] [$k] [] = $v ['status'] != 5 ? $show : '';
			$data['aaData'][$k][] = $v['ap_type'] > 0 ? $this->mOrder->apConfig($v['ap_type'])
			.'<br/><a class="ap-content-btn" href="javascript:void(0);"><span class="type">查看备注</span>
            		<span class="content hide">'.nl2br($v['ap_content']).'</span></a>' : '未报备';
			$data ['aaData'] [$k] [] = $this->mOrder->status ( $v ['status'], true );
			$btnConfig = array (
					array (
							'label' => '详情',
							'icon' => '<i class="fa fa-eye"></i>',
							'attr' => array (
									'href' => getUrl ( 'deliveryman/order/details?id=' . $v ['id'] ),
									'class' => 'btn btn-xs btn-default', 
									'target' => '_bank'
							),
							'tag' => 'a',
							'permissions' => array (
									'module' => 'deliveryman',
									'key' => 'order-view'
							)
					) 
			);
			
			$data ['aaData'] [$k] [] = adminCreateBtn ( $btnConfig );
		}
		unset ( $data ['data'] );
		echo json_encode ( $data );
	}
	
	/**
	 * 获取区域列表
	 */
	public function getAreaByPid(){
	
		$this->loadModel('AdmSettingModel', 'mSetting', 'admin');
		$tA = $this->mUser->getCountyIds($this->userId, true);
		$id = array_merge($tA['province'], $tA['city'], $tA['county']);
		$pid = (int)get('pid');
		$tA = $this->mSetting->getLocationByPid($pid, $id);
		$data = [];
		foreach ($tA as $v){
			$data[] = [
					'id' => $v['id'],
					'name' => $v['name']
			];
		}
	
		$this->ajaxReturn(1, '', $data);
	}
}
